<?php
namespace app\crm\model;
use think\Model;
use think\Db;
use think\Cache;
use think\Loader;

class Serviceorder extends Model
{
	/**
     * 获取订单列表
     * @param int $page <页码>
     * @param int $limit <每页显示条数>
	 * @param int $where <查询条件>
     * @return array <订单列表信息>
     */
    public function getOrderData($page,$limit,$where)
    {
		$menuname = "Service Order";
		$p_menuname = $_SESSION['menu'][$menuname]; //父菜单
		$priv = $_SESSION["user_priv"][$p_menuname][$menuname];	
		$username = $_SESSION["user_info"]["username"];
		
        $count = Db::name('order_info')->where($where)->count();
        // 查询状态为1的用户数据 并且每页显示10条数据
        $dataList = Db::name('order_info')->where($where)->limit(($page-1)*$limit,$limit)->order("createtime desc")->select();
        $row_order_status = array('0'=>'未确认','1'=>'已确认','2'=>'<span style="color:#FF6600;">取消</span>','3'=>'<span style="color:#FF6600;">待审核</span>','4'=>'<span style="color:red;font-weight:bold;">退货</span>','5'=>'已分单','6'=>'部分分单','7'=>'未通过','8'=>"问题单");
		$row_pay_status = array('N'=>'未付款','M'=>'付款中','Y'=>'<span style="color:#9933CC;font-weight:bold;">已付款</span>');
		$row_shipping_status = array('0'=>'<span style="color:#FF9933;font-weight:bold;">未发货</sapn>','1'=>'已发货','2'=>'<span style="color:#0000FF;font-weight:bold;">收货确认</span>','3'=>'配货中','4'=>'已发货(部分商品)','5'=>'发货中');
		$row_shopping_name = $this->logisticsMode();
		$row_payment = array("1"=>"余额支付","2"=>"银行汇款/转帐","3"=>"货到付款");
		$row_logistics_state = array("0"=>"在途","1"=>"揽件","2"=>"疑难","3"=>"签收","4"=>"退签","5"=>"派件","6"=>"退回","7"=>"转投");
		$department = Cache::get('department');
		$users = Cache::get('users');
		$saleProgram = Cache::get('saleProgram');
		$i = 0;
        foreach ($dataList as &$val) {
            $val["dept_id"] = $department[$val["dept_id"]]["department_name"];
			$val["cn_name"] = $users[$val["createname"]]["cn_name"];
			$val["saleProgram"] = $saleProgram[$val["program_id"]]["program_name"];
			$order_status = $row_order_status[$val['order_status']];
			$val['order_status'] = $order_status;
			$pay_status = $row_pay_status[$val['pay_status']];
			$val['pay_status'] = $pay_status;
			
			$shopping_name = $row_shopping_name[$val['shopping_name']];
			$val['shopping_name'] = $shopping_name;
			
			$payment = $row_payment[$val['payment']];
			$val['payment'] = $payment;
			
			$shipping_status = $row_shipping_status[$val['shipping_status']];
			$val['shipping_status'] = $shipping_status;
			$val['order_status'] = $val['order_status']."  ".$val['pay_status']."   ".$val['shipping_status'];
			$val["logistics_state"] = $row_logistics_state[$val["logistics_state"]];
			$val['logistics_Info'] = str_replace('"','',$val['logistics_Info']);
			if($val["logistics_account"] && $val["logistics_state"]){
				$val["operating"] = "<a href='javascript:void(0);' onclick=\"viewLogisticsInfo("."'".$val["logistics_account"]."','".$val["logistics_state"]."','".$val["logistics_Info"]."'".")\" >查看物流</a>";
			}else{
				$val["operating"] = "";
			}
			
			//判断号码是否加密
			if($priv["encrypt_phone"] == "Y"){
				if($username != "admin"){
					$val["phone"] = substr($val["phone"],0,3)."*****".substr($val["phone"],-2);
				}
			}
			$i++;
        }
		unset($i);
		
        $rowsList = count($dataList) ? $dataList : false;
        $arrCate["code"] = 0;
        $arrCate["msg"] = '';
        $arrCate["count"] = $count;
        $arrCate["data"] = $rowsList;
        return $arrCate;
    }
	
	
	/**
	 * 添加订单
	 * @param  [arr]  $data [订单添加信息]
	 */
	public function insertOrder($data)
    {	
		//dump($_REQUEST);die;
		$username = $_SESSION["user_info"]["username"];
		$d_id = $_SESSION["user_info"]["d_id"];
		$order_num = date("YmdHis").$username;
		$info = explode(",",$data['info']);
		
		foreach($info as $vm){
			$goodInfo[] = explode("-",$vm);
		}
		
		foreach($goodInfo as $v){
			$price[] = $v[3];
			$g_id[] = $v[0];
			//$g_name[] = $v[4]."-".$v[2];
			//$g_name[] = $v[0]."`*`".$v[1]."`*`".$v[2]."`*`".$v[3]."`*`".$v[4]."`*`".$v[5]."`*`".$v[6]."`*`".$v[7];  //商品id-商品数量-商品单价-商品总价格-商品名称-商品货号-商品分类-商品品牌
			$g_name[] = array(
				"id"=>$v[0],			//商品id
				"goods_num"=>$v[1],		//商品数量
				"price"=>$v[2],			//商品单价
				"goods_money"=>$v[3],	//商品总价格
				"good_name"=>$v[4],		//商品名称
				"good_num"=>$v[5],		//商品货号
				"cat_name"=>$v[6],		//商品分类
				///"brand_name"=>$v[7],	//商品品牌
			);
			$nums[] = $v[1];
			$g_num[] = $v[4]."[".$v[5]."]*".$v[1];  //商品名称[商品货号]*商品数量
		}
		$goods_total = array_sum($nums);
		$cope_money = array_sum($price);
		$goods_id = implode(",",$g_id);
		//$goods_name = implode(",",$g_name);
		$goods_name = json_encode($g_name);
		$order_goods_num = implode(",",$g_num);
		
		$phone = $data['phone'];
		$telephone = $data['telephone'];
		
		$customer_code = $_REQUEST['customer_code'];
		$order_count = Db::name('order_info')->where("customer_code = '$customer_code' AND order_status = '1'")->count();
		//$order_type = $_REQUEST["order_type"]
		
		$arrData = array(
			"order_num"=>$order_num,
			"goods_id"=>$goods_id,
			"goods_total"=>$goods_total,
			"goods_name"=>$goods_name,
			"customer_code"=>$customer_code,
			"consignee"=>$data['consignee'],
			"createname"=>$username,
			"goods_amount"=>$data["goods_amount"],
			"dept_id"=>$d_id,
			"createtime"=>date("Y-m-d H:i:s"),
			"order_status"=>'3',           //状态
			"pay_status"=>'N',
			"shipping_status"=>'0',
			"delivery_address"=>$data['delivery_address'],
			"telephone"=>$telephone,
			"phone"=>$phone,
			"order_goods_num"=>$order_goods_num,
			"modify_price"=>empty($data['modify_price']) ? "N" : $data['modify_price'],
			"order_rank"=>$order_count+1
		);
		$processCache = Cache::get('processCache');
		if($data['modify_price']=="Y"){
			$arrData["audit_status"] = "T";
			$arrData["step_num"] = 1;
			$arrData["authorized_work_num"] = $processCache[1]["authorized_work_num"];
			$arrData["cope_money"]=$data["modify_money"];
			
		}else{
			$arrData["cope_money"]=$cope_money;
		}
		
		//print_r($arrData);die;
		
		$result = Db::name('order_info')->insert($arrData);
		if($result){
			$order_id = Db::name('order_info')->getLastInsID();
			$sql = "insert into xy_order_goods(goods_id,goods_num,goods_price,goods_money,order_id) values";
			$value = "";
			foreach($goodInfo as $row){
				$str = "(";
				$str .= "'" .$row[0]. "',";  	 //商品id
				$str .= "'" .$row[1]. "',";  	 //商品数量
				$str .= "'" .$row[2]. "',";  	 //商品价格
				$str .= "'" .$row[3]. "',";  	 //商品总价格
				$str .= "'" .$order_id. "'";	 //订单id---最后一个不需要","
				
				$str .= ")";
				$value .= empty($value)?"$str":",$str";
			}
			if( $value ){
				$sql .= $value;
				//dump($sql);die;
				$res = Db::execute($sql);
			}
			
			
			//添加订单时，添加一条跟踪信息,记录录音
			$arrF = array(
				"order_id" => $order_id,
				"action_time" => date("Y-m-d H:i:s"),
				"action_user" => $username,
				"order_status" => "T",
				"pay_status" => "N",
				"shipping_status" => "0",
				"action_description" => "添加订单"
			);
			
			$res = Db::name('order_action')->insert($arrF);
			//给客户资料更新最后下单时间
			$cus = Db::name('vip_customer_basic')->where("customer_code = '$customer_code'")->update(['last_order_time' => date("Y-m-d H:i:s")]);
		}
		if ($result){
            echo json_encode(array('success'=>true,'msg'=>'添加成功！'));
        } else {
            echo json_encode(array('msg'=>'添加失败！'));
        }
	}
	
	/**
	 * 根据订单id获取订单信息
	 * @param  [int]  $id 		 [订单id]
	 * @return [arr]  $arrData   [订单详情]
	 */
	public function getOrderDetail($id)
	{
		$fields = "id,consignee,createtime,phone,telephone,delivery_address,modify_price,cope_money,order_status,pay_status,shipping_status,delivery_order,payment,customer_code,order_num,createname,step_num,audit_status";
		$arrData = Db::name('order_info')->field($fields)->where('id',$id)->find();
        return $arrData;
	}
	
	/**
	 * 根据id获取订单里的商品
	 * @param  [int]  $id        [订单id]
	 * @return [arr]  $arrCate   [订单商品信息]
	 */
	public function getOrderGoods($id)
	{
		$count = Db::name('order_goods')->where("order_id = $id")->count();
        // 查询状态为1的用户数据 并且每页显示10条数据
        $dataList = Db::name('order_goods')->where("order_id = $id")->select();
        $goodsInfo = Cache::get('goodsInfo');
		foreach($dataList as &$val){
			$val["good_name"] = $goodsInfo[$val["goods_id"]]["good_name"];
			$val["good_num"] = $goodsInfo[$val["goods_id"]]["good_num"];
			$val["price"] = $val["goods_price"];
			$val["cat_name"] = $goodsInfo[$val["goods_id"]]["cat_name"];
			$val["simple_description"] = $goodsInfo[$val["goods_id"]]["simple_description"];
		}
        $rowsList = count($dataList) ? $dataList : false;
        $arrCate["code"] = 0;
        $arrCate["msg"] = '';
        $arrCate["count"] = $count;
        $arrCate["data"] = $rowsList;
        return $arrCate;
	}
	
	/**
	 * 根据id获取订单的操作记录
	 * @param  [int]  $id        [订单id]
	 * @return [arr]  $arrCate   [订单操作记录]
	 */
	public function orderAction($id)
	{
		$count = Db::name('order_action')->where("order_id = $id")->count();
        // 查询状态为1的用户数据 并且每页显示10条数据
        $dataList = Db::name('order_action')->where("order_id = $id")->select();
		$row_order_status = array('0'=>'未确认','1'=>'已确认','2'=>'<span style="color:#FF6600;">取消</span>','3'=>'<span style="color:#FF6600;">待审核</span>','4'=>'<span style="color:red;font-weight:bold;">退货</span>','5'=>'已分单','6'=>'部分分单','7'=>'未通过','8'=>"问题单","T"=>"待审核");
		$row_pay_status = array('N'=>'未付款','M'=>'付款中','Y'=>'<span style="color:#9933CC;font-weight:bold;">已付款</span>');
		$row_shipping_status = array('0'=>'<span style="color:#FF9933;font-weight:bold;">未发货</sapn>','1'=>'已发货','2'=>'<span style="color:#0000FF;font-weight:bold;">收货确认</span>','3'=>'配货中','4'=>'已发货(部分商品)','5'=>'发货中');
		$users = Cache::get('users');
		foreach($dataList as &$val){
			$val["action_user"] = $users[$val["action_user"]]["cn_name"];
			$val["order_status"] = $row_order_status[$val["order_status"]];
			$val["pay_status"] = $row_pay_status[$val["pay_status"]];
			$val["shipping_status"] = $row_shipping_status[$val["shipping_status"]];
		}
        $rowsList = count($dataList) ? $dataList : false;
        $arrCate["code"] = 0;
        $arrCate["msg"] = '';
        $arrCate["count"] = $count;
        $arrCate["data"] = $rowsList;
        return $arrCate;
	}
	

	/**
	 * 记录订单操作动态
	 * @param  [int]  $id          [description]
	 * @param  [str]  $description [description]
	 * @return [type]              [description]
	 */
	public function saveTrack($id,$description){
		$username = $_SESSION["user_info"]["username"];
		$arrD = Db::name("order_info")->field("customer_code,order_status,pay_status,shipping_status")->where("id = '$id'")->find();
		$customer_code = $arrD["customer_code"];
		$arrF = array(
			"order_id" => $id,
			"action_time" => date("Y-m-d H:i:s"),
			"action_user" => $username,
			"order_status" => $arrD["order_status"],
			"pay_status" => $arrD["pay_status"],
			"shipping_status" => $arrD["shipping_status"],
			"action_description" => $description,
			"uniqueid"=>$_SESSION[$username."_order"][$customer_code],
		);
		$res = Db::name("order_action")->insert($arrF);
	}
	
	/**
   	 * 获取物流方式 
   	 */
	public function logisticsMode(){
		$arrData = Db::name('order_logistics_mode')->order("id asc")->field("id,logistics_name as name")->select();
		foreach($arrData as $val){
			$arrF[$val["id"]] = $val["name"];
		}
		return $arrF;
	}
	
	/**
   	 * 获取界面物流方式 
   	 */
	public function getLogisticsMode(){
		$arrData = Db::name('order_logistics_mode')->order("id asc")->field("id,logistics_name as name")->select();
		return $arrData;
	}
}

?>

